package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.HistorySearchDto;
import com.heima.model.search.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojo.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service

public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    BehaviorFeign behaviorFeign;
    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 删除搜索历史
     *
     * @param dto@return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        //检查参数
        if (dto.getHistoryId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //删除
        Query query = Query
                .query(Criteria.where("entryId").is(user.getId()).and("id").is(dto.getHistoryId()));
        mongoTemplate.remove(query,ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询搜索历史
     *
     * @param userSearchDto
     * @return
     */
    @Override
    public ResponseResult findUserSearch(UserSearchDto userSearchDto) {
        //检查参数
        List<ApUserSearch> userSearchesList = new ArrayList<>();
        ApUser user = AppThreadLocalUtils.getUser();
        if (userSearchDto != null && user != null) {

            Integer entryId = user.getId();
            //查询实体
            ApBehaviorEntry apBehaviorEntry = behaviorFeign.
                    findByUserIdOrEquipmentId(entryId, userSearchDto.getEquipmentId());
            if (apBehaviorEntry != null) {
                // 查询当前用户的搜索列表  按照时间倒序 .limit(userSearchDto.getPageSize())
                userSearchesList =  mongoTemplate.find(Query.query(Criteria.where("entryId").is(entryId))
                        .with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);
                return ResponseResult.okResult(userSearchesList);
            }

        }


        return ResponseResult.okResult(userSearchesList);
    }

    /**
     * 保存用户搜索历史记录
     *
     * @param userSearchDto
     */
    @Override
    //异步执行
    @Async("taskExecutor")
    public void insert(UserSearchDto userSearchDto) {
        //检查参数
        String searchWords = userSearchDto.getSearchWords();
        Integer entryId = userSearchDto.getEntryId();
        if (entryId == null || StringUtils.isBlank(searchWords)) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //查询行为实体
        ApBehaviorEntry apBehaviorEntry = behaviorFeign
                .findByUserIdOrEquipmentId(entryId, userSearchDto.getEquipmentId());
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        log.info("ApUserSearchServiceImpl insert entryId:{}, searchWords:{}", entryId, searchWords);

        //查询关键词是否存在
        ApUserSearch apUserSearch = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(entryId)
                .and("keyword").is(searchWords)), ApUserSearch.class);
        //查询当前用户关键词列表
        List<ApUserSearch> apUserSearcheList = mongoTemplate.find(Query.query(Criteria.where("entryId").is(entryId))
                .with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);
        //存在则更新时间，更新状态
        if (apUserSearcheList != null) {
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }
        //3.2 不存在则新增, 判断当前历史记录是否超过10条记录
        apUserSearch = new ApUserSearch();
        apUserSearch.setCreatedTime(new Date());
        apUserSearch.setEntryId(entryId);
        apUserSearch.setKeyword(searchWords);
        if (apUserSearcheList == null || apUserSearcheList.size() < 10) {
            mongoTemplate.save(apUserSearch);
        } else {
            ApUserSearch lastUserSearch = apUserSearcheList.get(apUserSearcheList.size() - 1);// 获取最后一条记录
            Query query = Query.query(Criteria.where("id").is(lastUserSearch.getId()));
            mongoTemplate.findAndReplace(query, apUserSearch);
        }


    }

}
